<?php
namespace app\api\controller;
use app\api\model\User as UserModel;

class User extends Controller
{
    public function search($id){
        $model=new UserModel();
        $user=$model->where('id','=',$id)->find();

        return $this->renderSuccess($user,'获取用户成功');
    }
public function getUserList($query){
    $model=new UserModel();
    $condition['username'] =array('like',"%$query%");
    $condition['email'] =array('like',"%$query%");
    $condition['mobile'] =array('like',"%$query%");
    $userList=$model->where($condition)->select();
    return $this->renderSuccess($userList,'获取用户列表成功');
}
    public function index($username,$password,$email,$mobile)
    {
        $model = new UserModel();
        $user = $model->where('username','=',$username)->find();
        if(empty($user)){return $this->renderError('用户不存在');}
        if($password==$user->password){return $this->renderError('新密码不能与旧密码一致');}
        if($user->email!=$email){return $this->renderError('邮箱错误');}
        if($user->mobile!=$mobile){return $this->renderError('手机号错误');}
        return $this->renderSuccess($user, '获取用户数据成功');
    }
    public function edit($id){
        $model=new UserModel();
        if ($model->update($this->request->param())->where('id','=',$id)) {

            return $this->renderSuccess([],'修改成功');
        } else {
            return $this->renderError('修改失败');
        }
    }

    public function add($username)
    {
        $model = new UserModel();
        $user=$model->where('username','=',$username)->find();
        if($user){return $this->renderError('该用户名已存在');}
        if ($model->save($this->request->param())) {
            $new_user = $model->where(['id' => $model->getLastInsID()])->find();
            return $this->renderSuccess($new_user, '添加成功');
        } else {
            return $this->renderError('添加失败');
        }
    }
    public function del($id)
    {
        if (UserModel::destroy($id)) {
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }
    public function upload(){
        // 获取表单上传文件 例如上传了001.jpg
        $file = request()->file('image');
        // 移动到框架应用根目录/uploads/ 目录下
        $info = $file->move( '../public/uploads/user');
        if($info){
            // 成功上传后 获取上传信息
            $_POST = 'http://audio.com:8088/service/public/uploads/user/'.$info->getSaveName();
            echo $_POST;
        }else{
            // 上传失败获取错误信息
            echo $file->getError();
        }
    }
}
